using B.S.XZYData.Api.Wrter.Application.Command.Team;
using B.S.XZYData.Domain.XZY;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure;
using MediatR;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Team
{
    /// <summary>
    /// 删除班组处理器
    /// </summary>
    public class DeleteTeamHandler : IRequestHandler<DeleteTeamCommand, ApiResult<bool>>
    {
        private readonly MyDbContext _dbContext;

        public DeleteTeamHandler(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<ApiResult<bool>> Handle(DeleteTeamCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (request.TeamIds == null || !request.TeamIds.Any())
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnum.Error,
                        Msg = "请选择要删除的班组",
                        Data = false
                    };
                }

                // 先逻辑删除班组成员
                var memberUpdateCount = await _dbContext.Updateable<TeamMember>()
                    .SetColumns(x => x.IsDeleted == true)
                    .Where(x => request.TeamIds.Contains(x.TeamId) && !x.IsDeleted)
                    .ExecuteCommandAsync();

                // 再逻辑删除班组
                var teamUpdateCount = await _dbContext.Updateable<B.S.XZYData.Domain.XZY.Team>()
                    .SetColumns(x => x.IsDeleted == true)
                    .Where(x => request.TeamIds.Contains(x.Id) && !x.IsDeleted)
                    .ExecuteCommandAsync();

                return new ApiResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = $"成功删除 {teamUpdateCount} 个班组",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Error,
                    Msg = $"删除班组失败: {ex.Message}",
                    Data = false
                };
            }
        }
    }
}
